<template>
  <transition-group class="message-container" name="list" tag="ul">
    <Message v-for="(msg, index) in messages" :key="msg.id" :message="msg.message" :type="msg.type"/>
  </transition-group>
</template>

<script lang="ts" setup>
import {ref, onMounted, getCurrentInstance} from 'vue'
import Message from './index.vue'

interface MessageOptions {
  id: number,
  message: string,
  type: 'success' | 'warning' | 'info' | 'error'
}

const messages = ref<MessageOptions[]>([])

const addMessage = (message: string, type: 'success' | 'warning' | 'info' | 'error') => {
  const id = Date.now()
  messages.value.push({id, message, type})
  console.log(message)
  setTimeout(() => {
    messages.value = messages.value.filter(msg => msg.id !== id)
  }, 3000)
}

onMounted(() => {
  const instance = getCurrentInstance()
  if (instance) {
    instance.appContext.provides.addMessage = addMessage
  }
})
</script>

<style lang="scss" scoped>
.message-container {
  position: fixed;
  top: 68px;
  left: 50%;
  max-width: 300px;
  transform: translateX(-50%);
  pointer-events: none;
  z-index: 1001;
}

.list-enter-active,
.list-leave-active {
  transition: all .5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
